#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os,sys,base64
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
from dataset import dic_
from keras.models import load_model
from PIL import Image
from BaseHTTPServer import HTTPServer as server,BaseHTTPRequestHandler as handler
import StringIO
from urllib import unquote
import numpy as np
from daemon.runner import DaemonRunner

path = os.path.abspath('.')

class App():

    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = path + '/logs/server-out.log'
        self.stderr_path = path + '/logs/server-err.log'
        self.pidfile_path =  path + '/proc/server.pid'
        self.pidfile_timeout = 5
    
    def run(self):

        #服务端口
        port = 4231

        #识别盒子位置
        boxs = [(5, 1, 17, 21), (17, 1, 29, 21), (29, 1, 41, 21), (41, 1, 53, 21)]

        #加载训练模型
        model = load_model(path + '/model.h5')

        #创建小型http服务
        class RequestHandler(handler):
            def writeHeaders(_self):
                _self.send_response(200)
                _self.send_header('Content-type', 'application/json')
                _self.end_headers()
            def do_POST(_self):
                _self.writeHeaders()
                length = _self.headers.getheader('content-length')
                data = _self.rfile.read(int(length))
	        imgData = unquote(data[5:])
                img = Image.open(StringIO.StringIO(base64.b64decode(imgData))).convert('L').convert('1')
                captcha = ''
                for x in range(len(boxs)):
                    arr = []
                    roi = img.crop(boxs[x])
                    roi = np.array(roi)
                    arr.append([roi])
                    arr = np.array(arr)
                    arr = model.predict(arr)
                    captcha += dic_[np.argmax(arr)]
	        print captcha
	        _self.wfile.write('{"status":"success","data":"' + captcha + '"}')
        httpd = server(('localhost', port), RequestHandler)
        sa = httpd.socket.getsockname()
        print 'Captcha Recognition Service Running on', sa[0], 'Port', sa[1], '...'
        httpd.serve_forever()

daemonRunner = DaemonRunner(App())
daemonRunner.do_action()
